package com.xxxx.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
import org.springframework.web.servlet.mvc.method.annotation.ViewNameMethodReturnValueHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 基础拦截器，通过@Configuration自行配置为Bean，可以配置成多个拦截器。
 *
 * @author obiteaaron
 * @since 2019/12/26
 */
public class BaseInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseInterceptor.class);

    private ApplicationContext applicationContext;

    protected InterceptorPreHandler interceptorPreHandler;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean checkResult = interceptorPreHandler.check(request, response, handler);
        if (!checkResult) {
            postInterceptor(request, response, handler);
            return false;
        } else {
            return true;
        }
    }

    /**
     * 拦截后处理
     */
    protected void postInterceptor(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果被拦截，返回信息
        if (((HandlerMethod) handler).getMethodAnnotation(ResponseBody.class) != null) {
            // 返回json
            HandlerMethod handlerMethod = new HandlerMethod(((HandlerMethod) handler).getBean(), ((HandlerMethod) handler).getMethod());
            Object returnValue = interceptorPreHandler.getResponseBody();
            MethodParameter returnValueType = handlerMethod.getReturnValueType(returnValue);
            applicationContext.getBean(RequestMappingHandlerAdapter.class).getReturnValueHandlers();
            RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor = findRequestResponseBodyMethodProcessor();
            requestResponseBodyMethodProcessor.handleReturnValue(returnValue, returnValueType, new ModelAndViewContainer(), new ServletWebRequest(request, response));
            // end
        } else {
            // 返回页面
            HandlerMethod handlerMethod = new HandlerMethod(((HandlerMethod) handler).getBean(), ((HandlerMethod) handler).getMethod());
            String viewName = interceptorPreHandler.getViewName();
            MethodParameter returnValueType = handlerMethod.getReturnValueType(viewName);
            ViewNameMethodReturnValueHandler viewNameMethodReturnValueHandler = findViewNameMethodReturnValueHandler();
            ModelAndViewContainer modelAndViewContainer = new ModelAndViewContainer();
            // viewNameMethodReturnValueHandler 内的实现非常简单，其实可以不用这个的，直接new ModelAndViewContainer()就好了。
            viewNameMethodReturnValueHandler.handleReturnValue(viewName, returnValueType, modelAndViewContainer, new ServletWebRequest(request, response));

            // 抛出异常由Spring处理
            ModelMap model = modelAndViewContainer.getModel();
            ModelAndView modelAndView = new ModelAndView(modelAndViewContainer.getViewName(), model, modelAndViewContainer.getStatus());
            throw new ModelAndViewDefiningException(modelAndView);
            // end
        }
    }

    private RequestResponseBodyMethodProcessor findRequestResponseBodyMethodProcessor() {
        RequestMappingHandlerAdapter requestMappingHandlerAdapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);
        for (HandlerMethodReturnValueHandler value : Objects.requireNonNull(requestMappingHandlerAdapter.getReturnValueHandlers())) {
            if (value instanceof RequestResponseBodyMethodProcessor) {
                return (RequestResponseBodyMethodProcessor) value;
            }
        }
        // SpringMVC的环境下一定不会走到这里
        throw new UnsupportedOperationException("cannot find RequestResponseBodyMethodProcessor from RequestMappingHandlerAdapter by Spring Context.");
    }

    private ViewNameMethodReturnValueHandler findViewNameMethodReturnValueHandler() {
        RequestMappingHandlerAdapter requestMappingHandlerAdapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);
        for (HandlerMethodReturnValueHandler value : Objects.requireNonNull(requestMappingHandlerAdapter.getReturnValueHandlers())) {
            if (value instanceof ViewNameMethodReturnValueHandler) {
                return (ViewNameMethodReturnValueHandler) value;
            }
        }
        // SpringMVC的环境下一定不会走到这里
        throw new UnsupportedOperationException("cannot find ViewNameMethodReturnValueHandler from RequestMappingHandlerAdapter by Spring Context.");
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void setInterceptorPreHandler(InterceptorPreHandler interceptorPreHandler) {
        this.interceptorPreHandler = interceptorPreHandler;
    }

    public interface InterceptorPreHandler {
        /**
         * @see HandlerInterceptor#preHandle(HttpServletRequest, HttpServletResponse, Object)
         */
        boolean check(HttpServletRequest request, HttpServletResponse response, Object handler);

        /**
         * 拦截后返回的视图名称
         *
         * @see ModelAndView
         * @see ViewNameMethodReturnValueHandler
         */
        String getViewName();

        /**
         * 拦截后返回的对象
         *
         * @see ResponseBody
         * @see RequestResponseBodyMethodProcessor
         */
        Object getResponseBody();
    }
}
